package com.ruoyi.fun.service.impl;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import com.ruoyi.fun.mapper.SysDeploymentLogMapper;
import com.ruoyi.fun.domain.SysDeploymentLog;
import com.ruoyi.fun.domain.SysWechatConfig;
import com.ruoyi.fun.service.ISysDeploymentLogService;
import com.ruoyi.fun.service.ISysWechatConfigService;

/**
 * 部署记录Service业务层处理
 * 
 * @author Dreamyy
 * @date 2025-09-10
 */
@Service
public class SysDeploymentLogServiceImpl implements ISysDeploymentLogService 
{
    @Autowired
    private SysDeploymentLogMapper sysDeploymentLogMapper;

    @Autowired
    private ISysWechatConfigService sysWechatConfigService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 查询部署记录
     * 
     * @param id 部署记录主键
     * @return 部署记录
     */
    @Override
    public SysDeploymentLog selectSysDeploymentLogById(Long id)
    {
        return sysDeploymentLogMapper.selectSysDeploymentLogById(id);
    }

    /**
     * 查询部署记录列表
     * 
     * @param sysDeploymentLog 部署记录
     * @return 部署记录
     */
    @Override
    public List<SysDeploymentLog> selectSysDeploymentLogList(SysDeploymentLog sysDeploymentLog)
    {
        // 自动添加当前登录组织的过滤条件
        try {
            Long currentDeptId = SecurityUtils.getDeptId();
            if (currentDeptId != null) {
                sysDeploymentLog.setDeptId(currentDeptId);
            }
        } catch (Exception e) {
            System.out.println("[部署记录查询] 获取当前组织ID失败: " + e.getMessage());
            // 如果获取失败，继续执行查询但不添加组织过滤条件
        }
        return sysDeploymentLogMapper.selectSysDeploymentLogList(sysDeploymentLog);
    }

    /**
     * 新增部署记录
     * 
     * @param sysDeploymentLog 部署记录
     * @return 结果
     */
    @Override
    public int insertSysDeploymentLog(SysDeploymentLog sysDeploymentLog)
    {
        sysDeploymentLog.setCreateTime(DateUtils.getNowDate());
        // 设置部署状态为进行中（2）
        sysDeploymentLog.setDeploymentStatus("2");
        int result = sysDeploymentLogMapper.insertSysDeploymentLog(sysDeploymentLog);
        
        // 获取当前用户的组织ID，在主线程中获取
        Long currentOrgId = null;
        try {
            currentOrgId = SecurityUtils.getDeptId();
        } catch (Exception e) {
            System.out.println("[部署回调] 获取当前组织ID失败: " + e.getMessage());
        }
        
        // 插入成功后异步调用外部接口，不等待响应
        if (result > 0) {
            // 使用新线程异步调用外部接口
            final Long orgId = currentOrgId;
            new Thread(() -> {
                try {
                    callExternalApi(sysDeploymentLog, orgId);
                } catch (Exception e) {
                    System.err.println("[部署回调] 异步调用外部接口异常: " + e.getMessage());
                    e.printStackTrace();
                }
            }).start();
        }
        
        return result;
    }

    /**
     * 调用外部接口
     * 
     * @param sysDeploymentLog 部署记录
     * @param orgId 组织ID
     */
    private void callExternalApi(SysDeploymentLog sysDeploymentLog, Long orgId) {
        try {
            // 使用传入的组织ID
            System.out.println("[部署回调] 使用组织ID: " + orgId);
            
            if (orgId == null) {
                System.out.println("[部署回调] 组织ID为空，跳过外部接口调用");
                return;
            }
            
            // 根据orgId查询微信配置
            List<SysWechatConfig> wechatConfigs = sysWechatConfigService.selectSysWechatConfigByOrgId(String.valueOf(orgId));
            System.out.println("[部署回调] 查询微信配置结果，组织ID: " + orgId + ", 查询到配置数量: " + (wechatConfigs != null ? wechatConfigs.size() : 0));
            
            if (wechatConfigs == null || wechatConfigs.isEmpty()) {
                System.out.println("[部署回调] 未找到组织ID为 " + orgId + " 的微信配置，跳过外部接口调用");
                return;
            }
            
            SysWechatConfig wechatConfig = wechatConfigs.get(0);
            System.out.println("[部署回调] 找到微信配置: " + wechatConfig.getWechatName());
            
            // 构建最小化请求参数（仅保留 orgId 与 appId，上传秘钥URL可选）
            Map<String, Object> replacements = new HashMap<>();
            replacements.put("id", sysDeploymentLog.getId());
            replacements.put("wechat_appid", wechatConfig.getWechatAppid());
            // 统一使用传入的 orgId 作为 ORG_ID，避免前端产物中出现敏感或冗余信息
            replacements.put("ORG_ID", String.valueOf(orgId));
            // 可选：提供上传秘钥URL时，Node服务会执行上传；未提供则仅替换占位符
            if (wechatConfig.getUploadKeyUrl() != null && !wechatConfig.getUploadKeyUrl().isEmpty()) {
                replacements.put("upload_key_url", wechatConfig.getUploadKeyUrl());
            }

            System.out.println("[部署回调] 构建的请求参数: " + replacements);
            
            System.out.println("[部署回调] 准备调用外部接口，部署记录ID: " + sysDeploymentLog.getId() + ", 配置ID: " + sysDeploymentLog.getConfigId());
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(replacements, headers);
            
            // 调用外部接口
            String url = "http://127.0.0.1:3000";
            String response = restTemplate.postForObject(url, requestEntity, String.class);
            System.out.println("[部署回调] 外部接口调用成功，响应: " + response);
            
        } catch (Exception e) {
            System.err.println("[部署回调] 调用外部接口失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 修改部署记录
     * 
     * @param sysDeploymentLog 部署记录
     * @return 结果
     */
    @Override
    public int updateSysDeploymentLog(SysDeploymentLog sysDeploymentLog)
    {
        sysDeploymentLog.setUpdateTime(DateUtils.getNowDate());
        return sysDeploymentLogMapper.updateSysDeploymentLog(sysDeploymentLog);
    }

    /**
     * 批量删除部署记录
     * 
     * @param ids 需要删除的部署记录主键
     * @return 结果
     */
    @Override
    public int deleteSysDeploymentLogByIds(Long[] ids)
    {
        return sysDeploymentLogMapper.deleteSysDeploymentLogByIds(ids);
    }

    /**
     * 删除部署记录信息
     * 
     * @param id 部署记录主键
     * @return 结果
     */
    @Override
    public int deleteSysDeploymentLogById(Long id)
    {
        return sysDeploymentLogMapper.deleteSysDeploymentLogById(id);
    }

    /**
     * 部署完成回调，更新部署状态为已完成
     * 
     * @param id 部署记录主键
     * @return 结果
     */
    @Override
    public int completeDeployment(Long id)
    {
        // 查询当前部署记录
        SysDeploymentLog deploymentLog = sysDeploymentLogMapper.selectSysDeploymentLogById(id);
        if (deploymentLog == null) {
            return 0;
        }
        
        // 设置结束时间为当前时间
        deploymentLog.setEndTime(DateUtils.getNowDate());
        
        // 计算部署耗时（毫秒）
        if (deploymentLog.getStartTime() != null) {
            long duration = deploymentLog.getEndTime().getTime() - deploymentLog.getStartTime().getTime();
            deploymentLog.setDuration(duration);
        }
        
        // 设置部署状态为已完成（3）
        deploymentLog.setDeploymentStatus("3");
        
        // 更新记录
        return sysDeploymentLogMapper.updateSysDeploymentLog(deploymentLog);
    }

    /**
     * 部署失败回调，更新部署状态为失败并记录错误信息
     * 
     * @param id 部署记录主键
     * @param errorMessage 错误信息
     * @return 结果
     */
    @Override
    public int failDeployment(Long id, String errorMessage)
    {
        // 查询当前部署记录
        SysDeploymentLog deploymentLog = sysDeploymentLogMapper.selectSysDeploymentLogById(id);
        if (deploymentLog == null) {
            return 0;
        }
        
        // 设置结束时间为当前时间
        deploymentLog.setEndTime(DateUtils.getNowDate());
        
        // 计算部署耗时（毫秒）
        if (deploymentLog.getStartTime() != null) {
            long duration = deploymentLog.getEndTime().getTime() - deploymentLog.getStartTime().getTime();
            deploymentLog.setDuration(duration);
        }
        
        // 设置部署状态为失败（9）
        deploymentLog.setDeploymentStatus("9");
        
        // 设置错误信息
        deploymentLog.setErrorMessage(errorMessage);
        
        // 更新记录
        return sysDeploymentLogMapper.updateSysDeploymentLog(deploymentLog);
    }
}
